﻿using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Win32;

namespace RouterControl.Whs
{
    public static class RouterControlRegistry
    {
        private const string RouterControlRegistryHklmPath = @"SOFTWARE\Microsoft\Windows Home Server\RouterControl";
        private const string InstanceIdName = "InstanceId";
        private static readonly Guid GlobalMutexGuid = new Guid("{BD1564D7-5C62-4c77-B6C8-9E0EFA273C5E}");

        private static Guid _instanceGuid = Guid.Empty;

        public static Guid GetInstanceId()
        {
            // already known?
            if (_instanceGuid != Guid.Empty)
                return _instanceGuid;

            // open key
            var key = Registry.LocalMachine.OpenSubKey(RouterControlRegistryHklmPath);

            if (key == null)
            {
                key = Registry.LocalMachine.CreateSubKey(RouterControlRegistryHklmPath);
            }

            // get value
            var id = key.GetValue(InstanceIdName) as string;

            if (string.IsNullOrEmpty(id))
            {
                using (new GlobalMutex(GlobalMutexGuid).ForceLock)
                {
                    id = key.GetValue(InstanceIdName) as string;

                    if (string.IsNullOrEmpty(id))
                    {
                        _instanceGuid = Guid.NewGuid();
                        id = _instanceGuid.ToString();

                        key.SetValue(InstanceIdName, id);

                        return GetInstanceId();
                    }
                }
            }

            // got value
            _instanceGuid = new Guid(id);

            return _instanceGuid;
        }
    }
}
